import React, { Component, ReactElement } from 'react'
import { RouteComponentProps, withRouter } from 'react-router-dom'
import { hot } from 'react-hot-loader/root'
import moment from 'moment'
import Cookies from 'cookies-js'
import Master from './master'
import { UserContext } from './context'
import { connect } from 'react-redux'
import { AppState } from '@stores/interface'
import { SESSION_TOKEN, ZH_CN } from 'cache'
import { ConfigProvider } from 'antd'
import zhCN from 'antd/es/locale/zh_CN'
import enUS from 'antd/es/locale/en_US'
import { IntlProvider } from 'react-intl'
import en from '@langs/en'
import zh from '@langs/zh'

const mapStateToProps = (state: AppState) => {
  return ({
    user: state.get('user'),
    lang: state.getIn(['lang', 'lang'])
  })
}

type ReduxType = ReturnType<typeof mapStateToProps> & RouteComponentProps & { children: ReactElement }

class Index extends Component<ReduxType> {

  constructor(props: ReduxType) {
    super(props)
  }

  state = {
    loading: true,
  }

  componentDidMount() {
    const { user, lang } = this.props

    if (!user || !user.get('id')) {
      if (Cookies.get(SESSION_TOKEN)) {
        Api.user.fetchMe()
      } else {
        this.renderLoginPage()
        return
      }
    }

    if (user && user.get('id')) {
      if (this.state.loading) {
        this.setState({ loading: false })
      }
      return
    }

    this.setLang(lang)
  }

  componentDidUpdate(prevProps: ReduxType) {
    const { user, lang } = this.props
    if (prevProps.user !== user) {
      if (user && user.get('id')) {
        this.setState({ loading: false })
      } else if (!this.state.loading) {
        this.renderLoginPage()
      }
    }
    if (prevProps.lang !== lang && lang) {
      this.setLang(lang)
    }
  }

  render() {
    const { user, lang } = this.props
    if (this.state.loading || !user || !user.get('id')) return null

    return (
      <ConfigProvider locale={lang === ZH_CN ? zhCN : enUS}>
        <UserContext.Provider value={user}>
          <IntlProvider locale={lang} messages={lang === ZH_CN ? zh : en}>
            <Master {...this.props} />
          </IntlProvider>
        </UserContext.Provider>
      </ConfigProvider>
    )
  }

  renderLoginPage() {
    window.location.href = __EP_PASSPORT_URL__
  }

  setLang = (lang: string) => {
    moment.locale(lang === ZH_CN ? 'zh-cn' : 'en')
  }
}

export default hot(
  withRouter(connect(mapStateToProps)(Index))
)
